﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using System.ComponentModel;
using Innovox.NetTools;
using Innovox.YDeviceLib;
using System.Net;
using System.Windows.Threading;
using System.IO;
using System.Diagnostics;
using System.Reflection;

namespace FS_Config
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        ObservableCollection<IYDeviceInfo> _YdevCollection;

        public ObservableCollection<IYDeviceInfo> YdevCollection
        { get { return _YdevCollection; } }

	    YNetManager _yNet;
        bool _scanComplete;

        public Window1()
        {
            try
            {
                 Process Proc = Process.GetCurrentProcess(); 
                 long AffinityMask = (long)Proc.ProcessorAffinity;
                 AffinityMask &= 0x0001; // use only any of the first 1 available processors
                 Proc.ProcessorAffinity = (IntPtr)AffinityMask;

                 ProcessThread Thread = Proc.Threads[0];
                 AffinityMask = 0x0001; // use only the first processor, despite availability
                 Thread.ProcessorAffinity = (IntPtr)AffinityMask;

                _YdevCollection = new ObservableCollection<IYDeviceInfo>();
                InitializeComponent();
                Title += ", V" + Assembly.GetExecutingAssembly().GetName().Version.ToString();
				_yNet = new YNetManager();

               /* if (Environment.ProcessorCount >= 2)
                    _yNet.ThreadCount = 32;
                else if (Environment.ProcessorCount == 1)
                    _yNet.ThreadCount = 16;*/
                /* else
                    _yNet.ThreadCount = 16;*/
                _yNet.ThreadCount = 8;
                threadCountTextBox.Text = _yNet.ThreadCount.ToString();
                _scanComplete = true;
				_yNet.YDeviceDetected += DeviceDetected;
				_yNet.YNetScanComplete += ScanCompleted;
                _yNet.YNetScanProgress += ScanProgressed;
                _yNet.YNetScanLog += ScanLog;

                System.Net.IPAddress[] hostAddresses = System.Net.Dns.GetHostAddresses(System.Net.Dns.GetHostName());
                foreach (IPAddress ip in hostAddresses)
                    serverIpComboBox.Items.Add(ip.ToString());
                serverIpComboBox.SelectedItem = hostAddresses[0].ToString();
                UpdateModemConfigButtons();
                modemGrid.IsEnabled = false;
                
                PingRange pr = PingRange.GetNetworkIpRange();
                ipRangeStartTextBox.Text = pr.StartRange.ToString();
                ipRangeEndTextBox.Text = pr.EndRange.ToString();               
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }

		private void BuildDeviceTree()
		{
			deviceTreeView.Items.Clear();
			List<string> masterIps = new List<string>();

            foreach (KeyValuePair<IPAddress, YDevice> kvp in _yNet.Devices)
                if (kvp.Value.Modem.AccesType == ModemAccessType.Master)
                {
                    TreeViewItem masterItem = new TreeViewItem();
                    YDevice dev = kvp.Value;
                    masterItem.Header = dev.Modem.IpAddress + ", " + dev.Modem.AccessTypeName + ", Tx:" + dev.TxBitrate.ToString() + "Mbps, Rx:" + dev.RxBitrate.ToString() + "Mbps, Ping:" + dev.Ping + "ms";
                    AddChildDeviceToTree(masterItem, kvp.Value);
                    deviceTreeView.Items.Add(masterItem);
                }
		}

		public void AddChildDeviceToTree(TreeViewItem masterItem, YDevice parentDev)
		{
			foreach (string mac in parentDev.Modem.Childs)
			{
				foreach(KeyValuePair<IPAddress,YDevice> kvp in _yNet.Devices)
				{
					if (kvp.Value.Modem.MacAddress == mac)
					{
						TreeViewItem childItem = new TreeViewItem();
                        YDevice dev = kvp.Value;
                        string nodeDescrip = dev.Modem.IpAddress + ", ";
                        if(dev.Name != "" && dev.Name != null)
                            nodeDescrip += dev.ServerName;
                        else
                            nodeDescrip += dev.Modem.AccessTypeName;
                        nodeDescrip += ", " + dev.Name + ", Tx:" + dev.TxBitrate.ToString() + "Mbps, Rx:" + dev.RxBitrate.ToString() + "Mbps, Ping:" + dev.Ping + "ms"; 
                        childItem.Header = nodeDescrip;
						masterItem.Items.Add(childItem);

						AddChildDeviceToTree(childItem, kvp.Value);
						break;
					}
				}
			}
		}

		private void ScanCompleted(object sender, YNetScanCompletedEventArgs e)
		{
            this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate()
            {
                YNetManager yman = (YNetManager)sender;
                Dictionary<IPAddress, YDevice> devices = yman.Devices;
                
                taskLabel.Content = "Scan Complete";
				BuildDeviceTree();
                _scanComplete = true;
                modemGrid.IsEnabled = true;
                scanButton.IsEnabled = true;
                scanButton.Content = "Scan";
                clearButton.IsEnabled = true;
                exportButton.IsEnabled = true;
                taskProgressbar.Visibility = Visibility.Hidden;
                LoadSelectedDevice();
            });
		}

	    private void DeviceDetected(object sender, YNetDeviceDetectedEventArgs e)
	    {
            this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate()
            {
                if (e.device != null)
                {
                    lock (_YdevCollection)
                    {
                        _YdevCollection.Add((IYDeviceInfo)e.device);
                        if(e.OldDevice != null)
                            _YdevCollection.Remove((IYDeviceInfo)e.OldDevice);
                    }
                }
            });
	    }

        private void ScanProgressed(object sender, YNetScanProgressEventArgs e)
	    {
            this.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
            (ThreadStart)delegate()
            {
                taskProgressbar.Value = e.Value;
            });
	    }

        private void ScanLog(object sender, YNetScanLogEventArgs e)
        {
            this.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
            (ThreadStart)delegate()
            {
                LogMessage(e.Message);
            });
        }

	    GridViewColumnHeader _lastHeaderClicked = null;
	    ListSortDirection _lastDirection = ListSortDirection.Ascending;

	    void GridViewColumnHeaderClickedHandler(object sender, RoutedEventArgs e)
	    {
            if (_scanComplete)
            {
                GridViewColumnHeader headerClicked = e.OriginalSource as GridViewColumnHeader;
                ListSortDirection direction;

                if (headerClicked != null && headerClicked.Column != null)
                {
                    if (_lastHeaderClicked != null)
                    {
                        _lastHeaderClicked.Column.HeaderTemplate = null;
                    }

                    if (headerClicked != _lastHeaderClicked)
                    {
                        direction = ListSortDirection.Ascending;
                    }
                    else
                    {
                        if (_lastDirection == ListSortDirection.Ascending)
                        {
                            direction = ListSortDirection.Descending;
                        }
                        else
                        {
                            direction = ListSortDirection.Ascending;
                        }
                    }

                    //string header = headerClicked.Column.Header as string;
                    Binding binding = (Binding)headerClicked.Column.DisplayMemberBinding;
                    string header = binding.Path.Path;

                    Sort(header, direction);

                    if (direction == ListSortDirection.Ascending)
                    {
                        headerClicked.Column.HeaderTemplate =
                            Resources["HeaderTemplateArrowUp"] as DataTemplate;
                    }
                    else
                    {
                        headerClicked.Column.HeaderTemplate =
                            Resources["HeaderTemplateArrowDown"] as DataTemplate;
                    }

                    _lastHeaderClicked = headerClicked;
                    _lastDirection = direction;
                }
            }
	    }

	    private void Sort(string sortBy, ListSortDirection direction)
	    {
		    deviceListView.Items.SortDescriptions.Clear();
		    SortDescription sd = new SortDescription(sortBy, direction);
		    deviceListView.Items.SortDescriptions.Add(sd);
		    deviceListView.Items.Refresh();
	    }

        private void clearListButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                deviceTreeView.Items.Clear();
                _YdevCollection.Clear();
                _yNet.Devices.Clear();
                ClearLog();
            }
            catch (Exception ex)
            {
                ShowErrors(ex.Message);
            }
        }

	    private void scanButton_Click(object sender, RoutedEventArgs e)
	    {
            try
            {
                string scanAction = scanButton.Content.ToString();

                if (scanAction.Contains("Scan"))
                {
                    modemGrid.IsEnabled = false;
                    //scanButton.IsEnabled = false;
                    exportButton.IsEnabled = false;
                    _scanComplete = false;
                    //_YdevCollection.Clear();
                    deviceTreeView.Items.Clear();
                    deviceTreeView.Items.Add("Scanning...");
                    taskLabel.Content = "Scanning:";
                    taskLabel.Visibility = Visibility.Visible;
                    taskProgressbar.Value = 0;
                    taskProgressbar.Visibility = Visibility.Visible;
                    SelectY1gControls(0);
                    SelectYfmControls(0);
                    //_yNet.Devices.Clear();
                    //modemChangeCouplingButton.Visibility = Visibility.Collapsed;
                    //modemChangeAccessTypeButton.Visibility = Visibility.Collapsed;

                    GetNumOfThreads();

                    if (_yNet.BeginScan(ipRangeStartTextBox.Text, ipRangeEndTextBox.Text) == false)
                    {
                        MessageBox.Show("Invalid Ip address range");
                        deviceTreeView.Items.Clear();
                        taskLabel.Content = "";
                        //BuildDeviceTree();
                        _scanComplete = true;
                        modemGrid.IsEnabled = true;
                        //scanButton.IsEnabled = true;
                        taskProgressbar.Visibility = Visibility.Hidden;
                    }
                    else
                    {
                        clearButton.IsEnabled = false;
                        scanButton.Content = "Stop";
                    }
                }
                else // stop scan
                {
                    taskLabel.Content = "Stopping Scan";
                    scanButton.IsEnabled = false;
                    scanButton.Content = "Stop";
                  //  saveMacAddress();
                    _yNet.StopScan();
                }
            }
            catch (Exception ex)
            {
                ShowErrors(ex.Message);

            }
	    }

        private void GetNumOfThreads()
        {
            int numOfThreads;
            if (int.TryParse(threadCountTextBox.Text, out numOfThreads) == false)
            {
                threadCountTextBox.Text = "1";
                numOfThreads = 1;
            }
            _yNet.ThreadCount = numOfThreads;
        }

        private void ReadY1gNV()
        {
            Y1G dev = (Y1G)_yNet.SelectedY1gs[0];
            y1gIpTextBox.Text = dev.Ip.ToString();
            y1gMACTextBox.Text = dev.Modem.MacAddress;
            dev.ReadY1gConfig();
            y1gNameTextBox.Text = dev.Value("/obix/name/");
            y1gLocationTextBox.Text = dev.Value("/obix/location/");
            y1gFlickRepsTextBox.Text = dev.Value("/obix/y1g/adv/flickReps/");
            y1gAutoOffDelayTextBox.Text = dev.Value("/obix/y1g/offDelay/");
            y1gPirSensTextBox.Text = dev.Value("/obix/y1g/pirSens/");
            y1gMotionMuteDelayTextBox.Text = dev.Value("/obix/y1g/adv/motionMuteDelay/");
            y1gLumFactorTextBox.Text = dev.Value("/obix/y1g/adv/lumFactor/");

            string autoMode = dev.Value("/obix/y1g/autoMode/");

            if (autoMode == null || autoMode.Length == 0)
                y1gAutoModeListBox.SelectedIndex = 0;
            else
            {
                foreach (ComboBoxItem it in y1gAutoModeListBox.Items)
                {
                    if (string.Compare(autoMode, (string)it.Tag) == 0)
                    {
                        y1gAutoModeListBox.SelectedItem = it;
                        break;
                    }
                }
            }
        }

        private void ShowErrors()
        {
            if (_yNet != null && _yNet.Errors.Count > 0)
            {
                string message = "";
                foreach (string error in _yNet.Errors)
                    message += error + "\r\n";
                MessageBox.Show(message, "Fs-Config Error");
            }
        }

        private void ShowErrors(string error)
        {
            if (error != null && error.Length > 0)
            {
                MessageBox.Show(error, "Fs-Config Error");
                LogMessage(error);
            }
        }

        private void LogMessage(string message)
        {
            if (message != null && message.Length > 0)
                loggerListView.Items.Add("-" + message);
        }

        private IEnumerable<string> GetLogMessageList()
        {
            IEnumerable<string> messages;
            messages = loggerListView.Items.Cast<string>();
            return messages;
        }

        private void ClearLog()
        {
            loggerListView.Items.Clear();
        }

        private void ReadY1gData()
        {
            Y1G dev = (Y1G)_yNet.SelectedY1gs[0];
            dev.ReadY1gData();
            //y1gButtonPressedTextBox.Text = dev.Value("/obix/y1g/buttonPressed/");
            y1gLatchActiveTextBox.Text = dev.Value("/obix/y1g/latchActive/");
            y1gLuminosityTextBox.Text = dev.Value("/obix/y1g/adv/luminosity/");
            y1gNetOnTextBox.Text = dev.Value("/obix/y1g/adv/networkOn/");
            y1gNoMotionTimeTextBox.Text = dev.Value("/obix/y1g/noMotionTime/");
            y1gSwitchStatusTextBox.Text = dev.Value("/obix/y1g/adv/switchStatus/");
            y1gButtonPressedTimerTextBox.Text = dev.Value("/obix/y1g/bPressLapse/");
            y1gCurrentVersionTextBox.Text = dev.FirmwareVersion;
        }

        private void ClearY1gIdPanel()
        {
            y1gIpTextBox.Text = "";
            y1gMACTextBox.Text = "";
        }

        private void ClearY1gNvPanel()
        {
            y1gNameTextBox.Text = "";
            y1gLocationTextBox.Text = "";
            //y1gFlickOnTimeTextBox.Text = "";
            //y1gFlickOffTimeTextBox.Text = "";
            y1gFlickRepsTextBox.Text = "";
            //y1gLedDimTextBox.Text = "";
            //y1gLedOffTimeTextBox.Text = "";
            //y1gLedOnTimeTextBox.Text = "";
            //y1gLumSensTextBox.Text = "";
            y1gAutoOffDelayTextBox.Text = "";
            y1gPirSensTextBox.Text = "";
            y1gMotionMuteDelayTextBox.Text = "";
            y1gLumFactorTextBox.Text = "";
            y1gAutoModeListBox.SelectedIndex = 0;
            y1gButtonPressedTimerTextBox.Text = "";
            y1gLatchActiveTextBox.Text = "";
           // y1gLocateDelayTextBox.Text = "";
        }

        private void ClearY1gControlPanel()
        {
            y1gColorComboBox.SelectedIndex = 0;
        }

        private void ClearY1gDataPanel()
        {
            y1gColorComboBox.SelectedIndex = 0;
            //y1gButtonPressedTextBox.Text = "";
            y1gLuminosityTextBox.Text = "";
            y1gNetOnTextBox.Text = "";
            y1gNoMotionTimeTextBox.Text = "";
            y1gSwitchStatusTextBox.Text = "";
        }

        private void ClearY1gPanel()
        {
            ClearY1gIdPanel();
            ClearY1gNvPanel();
            ClearY1gControlPanel();
            ClearY1gDataPanel();
        }

        private void SelectY1gControls(int numSelected)
        {
            ClearY1gPanel();

            if (numSelected == 0)
            {
                y1gNameTextBox.IsEnabled = false;
                y1gLocationTextBox.IsEnabled = false;
                y1gStackPanel.IsEnabled = false;
            }
            else if (numSelected == 1)
            {
                y1gNameTextBox.Text = _yNet.SelectedY1gs[0].Name;
                y1gLocationTextBox.Text = _yNet.SelectedY1gs[0].Location;
                y1gMACTextBox.Text = _yNet.SelectedY1gs[0].Mac;
                y1gIpTextBox.Text = _yNet.SelectedY1gs[0].Ip.ToString();
                y1gCurrentVersionTextBox.Text = _yNet.SelectedY1gs[0].FirmwareVersion;
                y1gNameTextBox.IsEnabled = true;
                y1gLocationTextBox.IsEnabled = true;
                y1gStackPanel.IsEnabled = true;
                y1gRefreshButton.IsEnabled = true;
                y1gReadNVButton.IsEnabled = true;
                //SaveMac_Click();
                //saveMacAddress();
            }
            else // >1
            {
                y1gNameTextBox.IsEnabled = false;
                y1gLocationTextBox.IsEnabled = false;
                y1gStackPanel.IsEnabled = true;
                y1gRefreshButton.IsEnabled = false;
                y1gReadNVButton.IsEnabled = false;
            }
        }

        private void UpdateModemConfigButtons()
        {
            Visibility buttonVis;
            if (deviceListView.SelectedItems.Count == 1)
            {
                IYDeviceInfo dev = (IYDeviceInfo)deviceListView.SelectedItems[0];
                if (dev.IsModemConfigurable())
                {
                    if (dev.ServerName == "Rx Master")
                        modemChangeAccessTypeButton.Content = "Change access type to Repeater";
                    else
                        modemChangeAccessTypeButton.Content = "Change access type to Master";

                    modemChangeCouplingButton.Content = "Change coupling type to " + dev.ModemNotSelectedCouplingTypeName;
                    //readWriteAccess.Content = "Change Power Mask ";

                    buttonVis = Visibility.Visible;
                }
                else
                    buttonVis = Visibility.Collapsed;
            }
            else
                buttonVis = Visibility.Collapsed;

            modemChangeCouplingButton.Visibility = buttonVis;
            modemChangeAccessTypeButton.Visibility = buttonVis;
            tmult.Visibility = buttonVis;
            gatewayOptions.Visibility = buttonVis;
       //     readWriteAccess.Visibility = buttonVis;
            this.InvalidateVisual();
        }

        private void LoadSelectedDevice()
        {
            if (modemFileNameTextBox.Text != "")
            {
                if (deviceListView.SelectedItems.Count > 0)
                    modemProgramFirmwareButton.IsEnabled = true;
                else
                    modemProgramFirmwareButton.IsEnabled = false;
            }
            _yNet.SelectedY1gs.Clear();
            _yNet.SelectedYfms.Clear();

            foreach (IYDeviceInfo y in deviceListView.SelectedItems)
            {
                YDevice dev = _yNet.Devices[y.Ip];
                if (dev.ServerName == "Y1G")
                    _yNet.SelectedY1gs.Add(dev);
                if (dev.ServerName == "YFM")
                    _yNet.SelectedYfms.Add(dev);
            }

            foreach (TabItem ti in deviceParamTabControl.Items)
            {
                if (ti.Header.ToString().StartsWith("Y1G"))
                {
                    if (_yNet.SelectedY1gs.Count > 1)
                        y1gTabItem.Header = "Y1G(" + _yNet.SelectedY1gs.Count.ToString() + ")";
                    else
                        y1gTabItem.Header = "Y1G";

                    SelectY1gControls(_yNet.SelectedY1gs.Count);

                }
                else if (ti.Header.ToString().StartsWith("YFM"))
                {
                    if (_yNet.SelectedYfms.Count > 1)
                        yfmTabItem.Header = "YFM(" + _yNet.SelectedYfms.Count.ToString() + ")";
                    else
                        yfmTabItem.Header = "YFM";

                    SelectYfmControls(_yNet.SelectedYfms.Count);
                }
            }
            /*
             // reading y1g and yfm data 
            try
            {
                if (_yNet.SelectedY1gs.Count == 1)
                {
                    this.Cursor = Cursors.Wait;
                    ReadY1gNV();
                    ReadY1gData();
                    this.Cursor = Cursors.Arrow;
                }

                if (_yNet.SelectedYfms.Count == 1)
                {
                    this.Cursor = Cursors.Wait;
                    ReadYfmNV();
                    ReadYfmData();
                    this.Cursor = Cursors.Arrow;
                }
            }
            catch (Exception ex)
            {
                ShowErrors(ex.Message);
                this.Cursor = Cursors.Arrow;
            }*/

            UpdateModemConfigButtons();            
        }

        private void deviceListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (_scanComplete)
                LoadSelectedDevice();
        }
        private ObixEntry[] GetMacAddress()
        {
            ObixEntry[] obixEntries;

            obixEntries = new ObixEntry[] { 
                                                new ObixEntry( "/obix/macAddress/",y1gMACTextBox.Text)};
            
            return obixEntries;
        }



        private ObixEntry[] GetY1gUserParameters()
        {
            ObixEntry[] obixEntries;
            if (_yNet.SelectedY1gs.Count > 1)
            {
                obixEntries = new ObixEntry[] { 
                                                new ObixEntry( "/obix/y1g/pirSens/", y1gPirSensTextBox.Text),
                                                new ObixEntry( "/obix/y1g/offDelay/", y1gAutoOffDelayTextBox.Text),
                                                new ObixEntry( "/obix/y1g/adv/flickReps/", y1gFlickRepsTextBox.Text)
                                              };

            }
            else
            {
                obixEntries = new ObixEntry[] { 
                                                new ObixEntry( "/obix/name/",y1gNameTextBox.Text),
                                                new ObixEntry( "/obix/location/",y1gLocationTextBox.Text),
                                                new ObixEntry( "/obix/y1g/pirSens/", y1gPirSensTextBox.Text),
                                                new ObixEntry( "/obix/y1g/offDelay/", y1gAutoOffDelayTextBox.Text),
                                                new ObixEntry( "/obix/y1g/adv/flickReps/", y1gFlickRepsTextBox.Text),
                                                new ObixEntry( "/obix/y1g/adv/motionMuteDelay/", y1gMotionMuteDelayTextBox.Text),
                                                new ObixEntry( "/obix/y1g/adv/lumFactor/", y1gLumFactorTextBox.Text)
                };
            }
            ComboBoxItem item = (ComboBoxItem)y1gAutoModeListBox.SelectedItem;
            string mode = (string)item.Tag;
            if (mode != "selectMode")
            {
                ObixEntry modeEntry = new ObixEntry("/obix/y1g/autoMode/", mode);
                ObixEntry[] obixEntriesWithMode = new ObixEntry[obixEntries.Length + 1];
                obixEntries.CopyTo(obixEntriesWithMode, 0);
                obixEntriesWithMode[obixEntries.Length] = modeEntry;
                return obixEntriesWithMode;
            }
            return obixEntries;
        }

        private void y1gSaveNVButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_scanComplete)
                {
                    this.Cursor = Cursors.Wait;
                    ObixEntry[] entries = GetY1gUserParameters();
                    //YDevice dev = _yNet.Devices[IPAddress.Parse(_YdevCollection[deviceListView.SelectedIndex].Ip)];
                    //dev.
                    GetNumOfThreads();
                    Y1G.WriteNvParamEntries(_yNet.SelectedY1gs, entries);
                    _yNet.BeginWrite(_yNet.SelectedY1gs, null);
                    if (_yNet.SelectedY1gs.Count == 1)
                    {
                        string name = _yNet.SelectedY1gs[0].Value("/obix/name/");
                        if( name != "" )
                            _yNet.SelectedY1gs[0].Name = name;
                    }
                    ShowErrors();
                    this.Cursor = Cursors.Arrow;
                }
            }
            catch (Exception ex)
            {
                ShowErrors(ex.Message);
                this.Cursor = Cursors.Arrow;
            }
        }    

        private void y1gReadNVButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_scanComplete)
                {
                    this.Cursor = Cursors.Wait;
                    ReadY1gNV();
                    this.Cursor = Cursors.Arrow;
                }
            }
            catch (Exception ex)
            {
                ShowErrors(ex.Message);
                this.Cursor = Cursors.Arrow;
            }
        }

        private void y1gLightOnButton_Click(object sender, RoutedEventArgs e)
        {
            if (_scanComplete)
            {
                this.Cursor = Cursors.Wait;
                ObixEntry[] obixEntries = new ObixEntry[] { new ObixEntry("/obix/y1g/latchActive/", "true") };
                foreach (YDevice dev in _yNet.SelectedY1gs)
                {
                    try
                    {
                        dev.Write(obixEntries);
                        ShowErrors(dev.ErrorMessage);
                    }
                    catch (Exception ex)
                    {
                        ShowErrors(ex.Message);
                    }
                }
                this.Cursor = Cursors.Arrow;
            }
        }

        private void y1gLightOffButton_Click(object sender, RoutedEventArgs e)
        {
            if (_scanComplete)
            {
                this.Cursor = Cursors.Wait;
                ObixEntry[] obixEntries = new ObixEntry[] { new ObixEntry("/obix/y1g/latchActive/", "false") };

                foreach (YDevice dev in _yNet.SelectedY1gs)
                {
                    try
                    {
                        dev.Write(obixEntries);
                        ShowErrors(dev.ErrorMessage);
                    }
                    catch (Exception ex)
                    {
                        ShowErrors(ex.Message);
                    }
                }
                this.Cursor = Cursors.Arrow;
            }
        }

        private void y1gFlickWarnButton_Click(object sender, RoutedEventArgs e)
        {
            if (_scanComplete)
            {
                this.Cursor = Cursors.Wait;
                ObixEntry[] obixEntries = new ObixEntry[] { new ObixEntry("/obix/y1g/flickWarn/", "true") };

                foreach (YDevice dev in _yNet.SelectedY1gs)
                {
                    try
                    {
                        dev.Write(obixEntries);
                        ShowErrors(dev.ErrorMessage);
                    }
                    catch (Exception ex)
                    {
                        ShowErrors(ex.Message);
                        this.Cursor = Cursors.Arrow;
                    }

                }
                this.Cursor = Cursors.Arrow;
            }
        }

        private void y1gColorComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (_scanComplete)
            {
                this.Cursor = Cursors.Wait;
                try
                {
                    ComboBoxItem item = (ComboBoxItem)y1gColorComboBox.SelectedItem;
                    string color = (string)item.Tag;

                    ObixEntry[] obixEntries = new ObixEntry[] { new ObixEntry("/obix/y1g/adv/ledColor/", color) };

                    YDevice dev = _yNet.SelectedY1gs[0];
                    dev.Write(obixEntries);
                    ShowErrors(dev.ErrorMessage);
                }
                catch (Exception ex)
                {
                    ShowErrors(ex.Message);
                }
                this.Cursor = Cursors.Arrow;
            }
        }

        private void y1gRefreshButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_scanComplete)
                {
                    this.Cursor = Cursors.Wait;
                    ReadY1gData();
                    this.Cursor = Cursors.Arrow;
                }
            }
            catch (Exception ex)
            {
                ShowErrors(ex.Message);
                this.Cursor = Cursors.Arrow;
            }

        }

        private void ReadYfmNV()
        {
            YDevice dev = _yNet.SelectedYfms[0];
            dev.ReadYfmConfig();
            LogMessage(dev.ErrorMessage);
            yfmIpTextBox.Text = dev.Ip.ToString();
            yfmMACTextBox.Text = dev.Modem.MacAddress;
            yfmNameTextBox.Text = dev.Value("/obix/name/");
            yfmLocationTextBox.Text = dev.Value("/obix/location/");

            int temp;
            string attribStr;

            yfmDimMinTextBox.Text = "";
            yfmDimTextBox.Text = "";
            yfmDimModeComboBox.SelectedIndex = 0;
            /*
             string autoMode = dev.Value("/obix/y1g/autoMode/");

            if (autoMode == null || autoMode.Length == 0)
                y1gAutoModeListBox.SelectedIndex = 0;
            else
            {
                foreach (ComboBoxItem it in y1gAutoModeListBox.Items)
                {
                    if (string.Compare(autoMode, (string)it.Tag) == 0)
                    {
                        y1gAutoModeListBox.SelectedItem = it;
                        break;
                    }
                }
            } 
             */

            attribStr = dev.Value("/obix/yfm/dimming/dim/");
            if (int.TryParse(attribStr, out temp))
            {
                yfmDimTextBox.IsEnabled = true;
                yfmDimTextBox.Text = attribStr;
                yfmDimModeComboBox.IsEnabled = true;
                yfmDimMinTextBox.IsEnabled = true;
                
                attribStr = dev.Value("/obix/yfm/dimming/dimMin/");
                if (int.TryParse(attribStr, out temp))
                {
                    yfmDimMinTextBox.Text = attribStr;
                    yfmDimMinTextBox.IsEnabled = true;
                }

                string dimMode = dev.Value("/obix/yfm/dimming/dimMode/");

                if (dimMode == null || dimMode.Length == 0)
                {
                    //yfmDimModeComboBox.IsEnabled = false;
                    yfmDimModeComboBox.SelectedIndex = 0;
                }
                else
                {
                    yfmDimModeComboBox.IsEnabled = true;
                    foreach (ComboBoxItem it in yfmDimModeComboBox.Items)
                    {
                        if (string.Compare(dimMode, (string)it.Tag) == 0)
                        {
                            yfmDimModeComboBox.SelectedItem = it;
                            break;
                        }
                    }
                }
            }
            else
            {
                yfmDimMinTextBox.IsEnabled = false;
                yfmDimModeComboBox.IsEnabled = false;
                yfmDimTextBox.IsEnabled = false;
            }

            attribStr = dev.Value("/obix/yfm/motionMuteDelay/");
            if (int.TryParse(attribStr, out temp))
            {
                yfmMuteDelayTextBox.IsEnabled = true;
                yfmMuteDelayTextBox.Text = attribStr;
            }
            else
            {
                yfmMuteDelayTextBox.IsEnabled = false;
                yfmMuteDelayTextBox.Text = "";
            }

            UpdateYfmPanels(dev);
         }

        private void UpdateYfmPanels(YDevice dev)
        {
            YfmRelayPanel[] parPanels = new YfmRelayPanel[] { yfmRelay1ParPanel, yfmRelay2ParPanel, yfmRelay3ParPanel, yfmRelay4ParPanel };
            YfmCommandPanel[] cmdPanels = new YfmCommandPanel[] { null, yfmRelay1CommandPanel, yfmRelay2CommandPanel, yfmRelay3CommandPanel, yfmRelay4CommandPanel };
            TextBox[] switchStatusTexbox = new TextBox[] { null, yfmSwitch1StatusTextBox, yfmSwitch2StatusTextBox, yfmSwitch3StatusTextBox, yfmSwitch4StatusTextBox };
            TextBox[] latchActiveTexbox = new TextBox[] { null, yfmLatchActive1TextBox, yfmLatchActive2TextBox, yfmLatchActive3TextBox, yfmLatchActive4TextBox };

            int i = 0;
            if (dev == null)
            {
                yfmMuteDelayTextBox.Text = "";
                //yfmButtonPressedTextBox.Text = "";
                yfmButtonPressedTimerTextBox.Text = "";
                yfmDimTextBox.Text = "";
            }

            foreach (YfmRelayPanel pan in parPanels)
            {
                i++;
                string uri = string.Format("/obix/yfm/relay{0}", i);
                string val = "";

                if (dev != null)
                {
                    uri = string.Format("/obix/yfm/relay{0}", i);
                    val = dev.Value(uri + "/offDelay/");
                }

                if (val == null || val == "")
                {
                    pan.Visibility = Visibility.Collapsed;
                    cmdPanels[i].Visibility = Visibility.Collapsed;
                    switchStatusTexbox[i].IsEnabled = false;
                    latchActiveTexbox[i].IsEnabled = false;
                    pan.yfmAutoOffDelayTextBox.Text = "";
                    switchStatusTexbox[i].Text = "";
                    latchActiveTexbox[i].Text = "";
                    //pan.yfmFlickOnTimeTextBox.Text = "";
                    //pan.yfmFlickOffTimeTextBox.Text = "";
                    pan.yfmFlickRepsTextBox.Text = "";
                    pan.yfmAutoModeListBox.SelectedIndex = 0;                    
                }
                else if (val != string.Empty)
                {
                    pan.Visibility = Visibility.Visible;
                    cmdPanels[i].Visibility = Visibility.Visible;
                    pan.yfmAutoOffDelayTextBox.Text = val;
                    switchStatusTexbox[i].IsEnabled = true;
                    latchActiveTexbox[i].IsEnabled = true;

                    //pan.yfmFlickOnTimeTextBox.Text = dev.Value(uri + "/flickOnTime/");// temp;
                    //pan.yfmFlickOffTimeTextBox.Text = dev.Value(uri + "/flickOffTime/");
                    pan.yfmFlickRepsTextBox.Text = dev.Value(uri + "/flickReps/");// temp;

                    string autoMode = dev.Value(uri + "/autoMode/");

                    if (autoMode == null || autoMode.Length == 0)
                        pan.yfmAutoModeListBox.SelectedIndex = 0;
                    else
                        pan.yfmAutoModeListBox.SelectedIndex = ObixObject.AutoModeDict[autoMode];
                }
            }
        }

        private void ReadYfmData()
        {
            YDevice dev = _yNet.SelectedYfms[0];
            dev.ReadYfmData();
            LogMessage(dev.ErrorMessage);
            //yfmButtonPressedTextBox.Text = dev.Value("/obix/yfm/buttonPressed/");
            yfmButtonPressedTimerTextBox.Text = dev.Value("/obix/yfm/bPressLapse/");

            if (yfmSwitch1StatusTextBox.IsEnabled)
            {
                yfmSwitch1StatusTextBox.Text = dev.Value("/obix/yfm/relay1/switchStatus/");
                yfmLatchActive1TextBox.Text = dev.Value("/obix/yfm/relay1/latchActive/");
            }
            if (yfmSwitch2StatusTextBox.IsEnabled)
            {
                yfmSwitch2StatusTextBox.Text = dev.Value("/obix/yfm/relay2/switchStatus/");
                yfmLatchActive2TextBox.Text = dev.Value("/obix/yfm/relay2/latchActive/");
            }
            if (yfmSwitch3StatusTextBox.IsEnabled)
            {
                yfmSwitch3StatusTextBox.Text = dev.Value("/obix/yfm/relay3/switchStatus/");
                yfmLatchActive3TextBox.Text = dev.Value("/obix/yfm/relay3/latchActive/");
            }
            if (yfmSwitch4StatusTextBox.IsEnabled)
            {
                yfmSwitch4StatusTextBox.Text = dev.Value("/obix/yfm/relay4/switchStatus/");
                yfmLatchActive4TextBox.Text = dev.Value("/obix/yfm/relay4/latchActive/");
            }

            yfmCurrentVersionTextBox.Text = dev.FirmwareVersion;
        }

		private void ClearYfmIdPanel()
		{
			yfmIpTextBox.Text = "";
			yfmMACTextBox.Text = "";
		}

		private void ClearYfmNvPanel()
		{
			yfmNameTextBox.Text = "";
			yfmLocationTextBox.Text = "";
		}

		private void ClearYfmPanel()
		{
			ClearYfmIdPanel();
			ClearYfmNvPanel();
		}

		private void SelectYfmControls(int numSelected)
		{
			ClearYfmPanel();

			if (numSelected == 0)
			{
				yfmNameTextBox.IsEnabled = false;
				yfmLocationTextBox.IsEnabled = false;
				yfmStackPanel.IsEnabled = false;
				yfmRelay1ParPanel.Visibility = Visibility.Collapsed;
				yfmRelay2ParPanel.Visibility = Visibility.Collapsed;
				yfmRelay3ParPanel.Visibility = Visibility.Collapsed;
				yfmRelay4ParPanel.Visibility = Visibility.Collapsed;
			}
			else if (numSelected == 1)
			{
                yfmNameTextBox.Text = _yNet.SelectedYfms[0].Name;
                yfmLocationTextBox.Text = _yNet.SelectedYfms[0].Location;
                yfmMACTextBox.Text = _yNet.SelectedYfms[0].Mac;
                yfmIpTextBox.Text = _yNet.SelectedYfms[0].Ip.ToString();
                yfmCurrentVersionTextBox.Text = _yNet.SelectedYfms[0].FirmwareVersion;
				yfmNameTextBox.IsEnabled = true;
				yfmLocationTextBox.IsEnabled = true;
				yfmStackPanel.IsEnabled = true;
				yfmRefreshButton.IsEnabled = true;
				yfmReadNVButton.IsEnabled = true;
                UpdateYfmPanels(null);
			}
			else // >1
			{
				yfmNameTextBox.IsEnabled = false;
				yfmLocationTextBox.IsEnabled = false;
				yfmStackPanel.IsEnabled = true;
				yfmRefreshButton.IsEnabled = false;
				yfmReadNVButton.IsEnabled = false;
			}
		}

        private void exportButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Configure save file dialog box

                Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
                dlg.FileName = "NetInfo"; // Default file name
                dlg.DefaultExt = ".csv"; // Default file extension
                dlg.Filter = "csv documents (.csv)|*.csv"; // Filter files by extension

                // Show save file dialog box
                Nullable<bool> result = dlg.ShowDialog();

                // Process save file dialog box results
                if (result == true)
                {
                    // Save document
                    string filename = dlg.FileName;
                    FileStream fs = File.Open(filename, FileMode.Create);
                    string header = "BPL Network Information\r\n" + DateTime.Now.ToString() + "\r\n" + "MAC,IP,TYPE,COUPLING,NAME,LOCATION,VERSION,TX BITRATE, RX BITRATE, PING MS\r\n";
                    fs.Write(Encoding.ASCII.GetBytes(header), 0, header.Length);

                    foreach (KeyValuePair<IPAddress, YDevice> kvp in _yNet.Devices)
                    {
                        string infoStr = kvp.Value.BuildInfoString();
                        fs.Write(Encoding.ASCII.GetBytes(infoStr), 0, infoStr.Length);
                    }
                    fs.Close();                    
                }
            }
            catch (Exception ex)
            {
                ShowErrors(ex.Message);
            }
        }

        private void y1gProgramFirmwareButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                MessageBoxResult result = MessageBox.Show("Are your sure you want to update the selected device firmware",
                                                            "Update warning", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                if (result == MessageBoxResult.Yes)
                {
                    this.Cursor = Cursors.Wait;
                    GetNumOfThreads();
                    _yNet.BeginUpgrade(_yNet.SelectedY1gs, y1gFileNameTextBox.Text);
                    string filename = y1gFileNameTextBox.Text;
                    FirmwareUpgradeWindow dlg = new FirmwareUpgradeWindow(_yNet, _yNet.SelectedY1gs, filename);
                    dlg.ShowDialog();
                    this.Cursor = Cursors.Arrow;
                }
            }
            catch (Exception ex)
            {
                ShowErrors(ex.Message);
                this.Cursor = Cursors.Arrow;
            }
        }

        private void y1gBrowseFirmwareButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
                dlg.FileName = ""; // Default file name
                dlg.DefaultExt = ".hex"; // Default file extension
                dlg.Filter = "hex file (.hex)|*.hex"; // Filter files by extension

                // Show save file dialog box
                Nullable<bool> result = dlg.ShowDialog();

                // Process save file dialog box results
                if (result == true)
                {
                    y1gProgramFirmwareButton.IsEnabled = true;
                    // Save document
                    string filename = dlg.FileName;
                    y1gFileNameTextBox.Text = filename;
                }
            }
            catch (Exception ex)
            {
                ShowErrors(ex.Message);
            }
        }
        /*
        private void YFirmwareProgressed(object sender, YDeviceUpdateProgressedEventArgs e)
        {
            this.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
            (ThreadStart)delegate()
            {
                //taskProgressbar.Value = e.Value;
            });
        }
*/
        private void yfmProgramFirmwareButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                MessageBoxResult result = MessageBox.Show("Are your sure you want to update the selected device firmware",
                                                            "Update warning", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                if (result == MessageBoxResult.Yes)
                {
                    this.Cursor = Cursors.Wait;
                    GetNumOfThreads();
                    _yNet.BeginUpgrade(_yNet.SelectedYfms, yfmFileNameTextBox.Text);
                    string filename = yfmFileNameTextBox.Text;
                    FirmwareUpgradeWindow dlg = new FirmwareUpgradeWindow(_yNet, _yNet.SelectedYfms, filename);
                    dlg.ShowDialog();
                    this.Cursor = Cursors.Arrow;
                }
            }
            catch (Exception ex)
            {
                ShowErrors(ex.Message);
                this.Cursor = Cursors.Arrow;
            }
        }

        private void yfmBrowseFirmwareButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
                dlg.FileName = ""; // Default file name
                dlg.DefaultExt = ".hex"; // Default file extension
                dlg.Filter = "hex file (.hex)|*.hex"; // Filter files by extension

                // Show save file dialog box
                Nullable<bool> result = dlg.ShowDialog();

                // Process save file dialog box results
                if (result == true)
                {
                    yfmProgramFirmwareButton.IsEnabled = true;
                    // Save document
                    string filename = dlg.FileName;
                    yfmFileNameTextBox.Text = filename;
                }
            }
            catch (Exception ex)
            {
                ShowErrors(ex.Message);
                this.Cursor = Cursors.Arrow;
            }

        }

        private void modemProgramFirmwareButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ModemAccessType modemType = ModemAccessType.Unknown;

                if (modemFileNameTextBox.Text != "")
                {
                    MessageBoxResult result = MessageBox.Show("Are your sure you want to update the selected modems firmware?",
                                                                "Update warning", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                    if (result == MessageBoxResult.Yes)
                    {
                        List<YDevice> devs = new List<YDevice>();//_yNet.GetDeviceList("Modem");

                        foreach (IYDeviceInfo y in deviceListView.SelectedItems)
                        {
                            YDevice dev = _yNet.Devices[y.Ip];
                            if (modemType == ModemAccessType.Unknown)
                                modemType = dev.Modem.AccesType;
                            else if (modemType != dev.Modem.AccesType)
                            {
                                MessageBox.Show("Master and repeater modems can't be updated at the same time. Change your modem selection.",
                                            "FS-Config - Update Error", MessageBoxButton.OK, MessageBoxImage.Error);
                                return;
                            }
                            //if(dev.Modem.AccesType ==  ModemAccessType.Repeater)
                            devs.Add(dev);
                        }

                        if (_yNet.BeginModemUpgrade(devs, (string)serverIpComboBox.SelectedItem, modemFileNameTextBox.Text))
                        {
                            FirmwareUpgradeWindow dlg = new FirmwareUpgradeWindow(_yNet, devs, modemFileNameTextBox.Text);
                            dlg.ShowDialog();
                        }
                        else
                        {
                            MessageBox.Show("The application has encountered a problem with the Tftp server. The upgrade process has stopped.",
                                            "FS-Config - Update Error", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ShowErrors(ex.Message);
            }
        }

        private void modemBrowseFirmwareButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
                dlg.FileName = ""; // Default file name
                dlg.DefaultExt = ".ftp"; // Default file extension
                dlg.Filter = "ftp file (.ftp)|*.ftp"; // Filter files by extension

                // Show save file dialog box
                Nullable<bool> result = dlg.ShowDialog();

                // Process save file dialog box results
                if (result == true)
                {
                    if (deviceListView.SelectedItems.Count > 0)
                        modemProgramFirmwareButton.IsEnabled = true;

                    string filename = dlg.FileName;
                    modemFileNameTextBox.Text = filename;
                }
                else
                    modemProgramFirmwareButton.IsEnabled = false;
            }
            catch (Exception ex)
            {
                ShowErrors(ex.Message);
            }
        }

        /*private void y1gLocateButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_scanComplete)
                {
                    int i;
                    if (y1gLocateDelayTextBox.Text == string.Empty || int.TryParse(y1gLocateDelayTextBox.Text, out i) == false)
                        y1gLocateDelayTextBox.Text = "10";

                    ObixEntry[] obixEntries = new ObixEntry[] { new ObixEntry("/obix/y1g/locateDelay/", y1gLocateDelayTextBox.Text) };

                    YDevice dev = _yNet.SelectedY1gs[0];
                    this.Cursor = Cursors.Wait;
                    dev.Write(obixEntries);
                    ShowErrors(dev.ErrorMessage);
                    this.Cursor = Cursors.Arrow;
                }
            }
            catch (Exception ex)
            {
                ShowErrors(ex.Message);
                this.Cursor = Cursors.Arrow;
            }
        }*/

        private ObixEntry[] GetYfmLocationName()
        {

            ObixEntry[] obixEntries = new ObixEntry[] { 
                                                        new ObixEntry( "/obix/name/",yfmNameTextBox.Text),
                                                        new ObixEntry( "/obix/location/",yfmLocationTextBox.Text)};

            return obixEntries;
        }

        private ObixEntry[] GetYfmUserParameters1()
        {
		    ComboBoxItem item = (ComboBoxItem) yfmRelay1ParPanel.yfmAutoModeListBox.SelectedItem;
          string mode = (string)item.Tag;

          ObixEntry[] obixEntries = new ObixEntry[] { 
                                                        new ObixEntry( "/obix/name/",yfmNameTextBox.Text),
                                                        new ObixEntry( "/obix/location/",yfmLocationTextBox.Text),
                                                        //new ObixEntry( "/obix/yfm/dimming/dimEnable/", yfmDimModeComboBox.IsChecked.ToString().ToLower()),
                                                        new ObixEntry( "/obix/yfm/dimming/dim/", yfmDimTextBox.Text),
                                                        new ObixEntry( "/obix/yfm/dimming/dimMin/", yfmDimMinTextBox.Text),
                                                        new ObixEntry( "/obix/yfm/motionMuteDelay/", yfmMuteDelayTextBox.Text),
                                                        new ObixEntry( "/obix/yfm/relay1/offDelay/", yfmRelay1ParPanel.yfmAutoOffDelayTextBox.Text),
                                                        //new ObixEntry( "/obix/yfm/relay1/flickOnTime/", yfmRelay1ParPanel.yfmFlickOnTimeTextBox.Text),
                                                        //new ObixEntry( "/obix/yfm/relay1/flickOffTime/", yfmRelay1ParPanel.yfmFlickOffTimeTextBox.Text),
                                                        new ObixEntry( "/obix/yfm/relay1/flickReps/", yfmRelay1ParPanel.yfmFlickRepsTextBox.Text),
                                                        new ObixEntry( "/obix/yfm/relay1/autoMode/", mode)
            };

          item = (ComboBoxItem)yfmDimModeComboBox.SelectedItem;
          mode = (string)item.Tag;
          if (mode != "selectMode")
          {
              ObixEntry modeEntry = new ObixEntry("/obix/yfm/dimming/dimMode/", mode);
              ObixEntry[] obixEntriesWithMode = new ObixEntry[obixEntries.Length + 1];
              obixEntries.CopyTo(obixEntriesWithMode, 0);
              obixEntriesWithMode[obixEntries.Length] = modeEntry;
              return obixEntriesWithMode;
          }
            return obixEntries;
        }

				private ObixEntry[] GetYfmUserParameters2()
				{
					ComboBoxItem item = (ComboBoxItem)yfmRelay2ParPanel.yfmAutoModeListBox.SelectedItem;
					string mode = (string)item.Tag;

					ObixEntry[] obixEntries = new ObixEntry[] { 
                                                        new ObixEntry( "/obix/yfm/relay2/offDelay/", yfmRelay2ParPanel.yfmAutoOffDelayTextBox.Text),
                                                       // new ObixEntry( "/obix/yfm/relay2/flickOnTime/", yfmRelay2ParPanel.yfmFlickOnTimeTextBox.Text),
                                                       // new ObixEntry( "/obix/yfm/relay2/flickOffTime/", yfmRelay2ParPanel.yfmFlickOffTimeTextBox.Text),
                                                        new ObixEntry( "/obix/yfm/relay2/flickReps/", yfmRelay2ParPanel.yfmFlickRepsTextBox.Text),
                                                        new ObixEntry( "/obix/yfm/relay2/autoMode/", mode)
            };

					return obixEntries;
				}

				private ObixEntry[] GetYfmUserParameters3()
				{
					ComboBoxItem item = (ComboBoxItem)yfmRelay3ParPanel.yfmAutoModeListBox.SelectedItem;
					string mode = (string)item.Tag;

					ObixEntry[] obixEntries = new ObixEntry[] { 
                                                        new ObixEntry( "/obix/yfm/relay3/offDelay/", yfmRelay3ParPanel.yfmAutoOffDelayTextBox.Text),
                                                        //new ObixEntry( "/obix/yfm/relay3/flickOnTime/", yfmRelay3ParPanel.yfmFlickOnTimeTextBox.Text),
                                                       // new ObixEntry( "/obix/yfm/relay3/flickOffTime/", yfmRelay3ParPanel.yfmFlickOffTimeTextBox.Text),
                                                        new ObixEntry( "/obix/yfm/relay3/flickReps/", yfmRelay3ParPanel.yfmFlickRepsTextBox.Text),
                                                        new ObixEntry( "/obix/yfm/relay3/autoMode/", mode)
            };

					return obixEntries;
				}

				private ObixEntry[] GetYfmUserParameters4()
				{
					ComboBoxItem item = (ComboBoxItem)yfmRelay4ParPanel.yfmAutoModeListBox.SelectedItem;
					string mode = (string)item.Tag;

					ObixEntry[] obixEntries = new ObixEntry[] { 
                                                        new ObixEntry( "/obix/yfm/relay4/offDelay/", yfmRelay4ParPanel.yfmAutoOffDelayTextBox.Text),
                                                        //new ObixEntry( "/obix/yfm/relay4/flickOnTime/", yfmRelay4ParPanel.yfmFlickOnTimeTextBox.Text),
                                                        //new ObixEntry( "/obix/yfm/relay4/flickOffTime/", yfmRelay4ParPanel.yfmFlickOffTimeTextBox.Text),
                                                        new ObixEntry( "/obix/yfm/relay4/flickReps/", yfmRelay4ParPanel.yfmFlickRepsTextBox.Text),
                                                        new ObixEntry( "/obix/yfm/relay4/autoMode/", mode)
            };

					return obixEntries;
				}

		private void yfmReadNVButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_scanComplete)
                {
                    this.Cursor = Cursors.Wait;
                    ReadYfmNV();
                    this.Cursor = Cursors.Arrow;
                }
            }
            catch (Exception ex)
            {
                ShowErrors(ex.Message);
                this.Cursor = Cursors.Arrow;
            }
        }

        private void yfmSaveNVButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_scanComplete)
                {
                    this.Cursor = Cursors.Wait;
                    ObixEntry[] entries = GetYfmUserParameters1();
                    GetNumOfThreads();
                    _yNet.Write(_yNet.SelectedYfms, entries);
                    if (_yNet.SelectedYfms.Count == 1)
                    {
                        string name = _yNet.SelectedYfms[0].Value("/obix/name/");
                        if (name != "")
                            _yNet.SelectedYfms[0].Name = name;
                    }
                    ShowErrors();

                    if (yfmRelay2ParPanel.Visibility == Visibility.Visible
                        && (_yNet.Errors.Count == 0))
                    {
                        entries = GetYfmUserParameters2();
                        _yNet.Write(_yNet.SelectedYfms, entries);
                        ShowErrors();
                    }
                    if (yfmRelay3ParPanel.Visibility == Visibility.Visible
                        && (_yNet.Errors.Count == 0))
                    {
                        entries = GetYfmUserParameters3();
                        _yNet.Write(_yNet.SelectedYfms, entries);
                        ShowErrors();

                    }
                    if (yfmRelay4ParPanel.Visibility == Visibility.Visible
                        && (_yNet.Errors.Count == 0))
                    {
                        entries = GetYfmUserParameters4();
                        _yNet.Write(_yNet.SelectedYfms, entries);
                        ShowErrors();
                    }
                    if (_yNet.SelectedYfms.Count == 1 && (_yNet.Errors.Count == 0))
                    {
                        entries = GetYfmLocationName();
                        _yNet.Write(_yNet.SelectedYfms, entries);
                        ShowErrors();
                    }
                    this.Cursor = Cursors.Arrow;
                }
            }
            catch (Exception ex)
            {
                ShowErrors(ex.Message);
                this.Cursor = Cursors.Arrow;
            }
        }

        private void DoYfmCommand(string uri, string val)
        {
            try
            {
                ObixEntry[] obixEntries = new ObixEntry[] { new ObixEntry(uri, val) };
                YDevice dev = _yNet.SelectedYfms[0];
                this.Cursor = Cursors.Wait;
                dev.Write(obixEntries);
                ShowErrors(dev.ErrorMessage);
                this.Cursor = Cursors.Arrow;
            }
            catch (Exception ex)
            {
                ShowErrors(ex.Message);
                this.Cursor = Cursors.Arrow;
            }
        }

        private void yfmRelayCommandPanel_LightOnButtonClicked(object sender, EventArgs e)
        {
            YfmCommandPanel yfmCmd = (YfmCommandPanel)sender;
            string uri = (string)yfmCmd.LightOffUri;

            DoYfmCommand(uri, "true");
        }

        private void yfmRelayCommandPanel_LightOffButtonClicked(object sender, EventArgs e)
        {
            YfmCommandPanel yfmCmd = (YfmCommandPanel)sender;
            string uri = (string)yfmCmd.LightOffUri;

            DoYfmCommand(uri, "false");
        }

        private void yfmRelayCommandPanel_FlickWarnButtonClicked(object sender, EventArgs e)
        {
            YfmCommandPanel yfmCmd = (YfmCommandPanel)sender;
            string uri = (string)yfmCmd.FlickWarnUri;

            DoYfmCommand(uri, "true");
        }

        private void yfmRefreshButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_scanComplete)
                {
                    this.Cursor = Cursors.Wait;
                    ReadYfmData();
                    this.Cursor = Cursors.Arrow;
                }
            }
            catch (Exception ex)
            {
                ShowErrors(ex.Message);
                this.Cursor = Cursors.Arrow;
            }

        }

        private string ChangeMacAddress(string macStr, int val)
        {
            string incMac = macStr;
            try
            {
                string[] macSubStr = modemMACTextBox.Text.Split(':');

                if (macSubStr.Length != 6)
                {
                    MessageBox.Show("Invalid MAC Address", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    return macStr;
                }

                long result = 0;

                foreach (string s in macSubStr)
                {
                    result <<= 8;
                    result += Int16.Parse(s, System.Globalization.NumberStyles.AllowHexSpecifier);

                }

                result += val;

                byte[] bytes = new byte[6];

                for (int i = 0; i < 6; i++)
                {
                    long temp = result & 0xff;
                    bytes[i] = (byte)temp;
                    result >>= 8;
                }

                incMac = string.Format("{0:x2}:{1:x2}:{2:x2}:{3:x2}:{4:x2}:{5:x2}",
                                     bytes[5], bytes[4], bytes[3], bytes[2], bytes[1], bytes[0]);
            }
            catch (Exception ex)
            {
                ShowErrors(ex.Message);
            }
            return incMac;
        }

        private void modemIncMacButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                modemMACTextBox.Text = ChangeMacAddress(modemMACTextBox.Text, 1);

                string macProgStr = modemMACTextBox.Text + "   " + DateTime.Now.ToString() + "\r\n";
                FileStream fs = File.Open("Mac.txt", FileMode.Append);
                fs.Write(Encoding.ASCII.GetBytes(macProgStr), 0, macProgStr.Length);
                fs.Close();
            }
            catch (Exception ex)
            {
                ShowErrors(ex.Message);
            }
        }

        private void modemDecMacButton_Click(object sender, RoutedEventArgs e)
        {
            modemMACTextBox.Text = ChangeMacAddress(modemMACTextBox.Text, -1);
        }

        private void modemProgramMacButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (modemMACTextBox.Text != "")
                {
                    if (deviceListView.SelectedItems.Count == 0)
                        MessageBox.Show("Select a device in the list view",
                                        "FS-Config - Mac Change Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    else if (deviceListView.SelectedItems.Count > 1)
                        MessageBox.Show("Select only one device at a time in the list view",
                                        "FS-Config - Mac Change Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    else
                    {
                        MessageBoxResult result = MessageBox.Show("Are your sure you want to change the MAC Address?",
                                                                    "Update warning", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                        if (result == MessageBoxResult.Yes)
                        {
                            YDevice dev = (YDevice)deviceListView.SelectedItem; // kvp.Value;
                            if (modemMACTextBox.Text.Contains(':'))
                                dev.Modem.MacAddress = modemMACTextBox.Text;    //new MAC address;
                            else
                            {
                                string mac = modemMACTextBox.Text.Substring(0, 2) + ":";
                                mac += modemMACTextBox.Text.Substring(2, 2) + ":";
                                mac += modemMACTextBox.Text.Substring(4, 2) + ":";
                                mac += modemMACTextBox.Text.Substring(6, 2) + ":";
                                mac += modemMACTextBox.Text.Substring(8, 2) + ":";
                                mac += modemMACTextBox.Text.Substring(10, 2);
                                dev.Modem.MacAddress = mac;
                            }

                            this.Cursor = Cursors.Wait;
                            if (_yNet.DoMACChange(dev))
                            {
                                string macProgStr = dev.Modem.MacAddress + "   " + DateTime.Now.ToString() + "\r\n";
                                FileStream fs = File.Open("Mac.txt", FileMode.Append);
                                fs.Write(Encoding.ASCII.GetBytes(macProgStr), 0, macProgStr.Length);
                                fs.Close();

                                MessageBox.Show("The application has changed the MAC Address. Please wait 40 seconds or more to rescan", "FS-Config - Mac Address changed", MessageBoxButton.OK, MessageBoxImage.Information);
                            }
                            else
                            {
                                MessageBox.Show("The application has encountered a problem Updating the MAC Address. The Change process has stopped.",
                                                "FS-Config - Mac Change Error", MessageBoxButton.OK, MessageBoxImage.Error);
                            }
                            this.Cursor = Cursors.Arrow;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ShowErrors(ex.Message);
                this.Cursor = Cursors.Arrow;
            }
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            if (_scanComplete == false)
                e.Cancel = true;
        }

        private void modemChangeAccessTypeButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (deviceListView.SelectedItems.Count == 0)
                    MessageBox.Show("Select a device in the list view",
                                    "FS-Config - Access Type change error", MessageBoxButton.OK, MessageBoxImage.Error);
                else if (deviceListView.SelectedItems.Count > 1)
                    MessageBox.Show("Select only one device at a time in the list view",
                                    "FS-Config - Access Type change error", MessageBoxButton.OK, MessageBoxImage.Error);
                else
                {
                    YDevice dev = (YDevice)deviceListView.SelectedItem; // kvp.Value;

                    if (dev.Modem.AccesType != ModemAccessType.Repeater && dev.Modem.AccesType != ModemAccessType.Master)
                        MessageBox.Show("The selected device is not of type Master or Repeater",
                                "FS-Config - Access Type change error", MessageBoxButton.OK, MessageBoxImage.Error);
                    else
                    {
                        string newTypeStr;
                        ModemAccessType newAccessType;
                        if (dev.Modem.AccesType == ModemAccessType.Master)
                        {
                            newAccessType = ModemAccessType.Repeater;
                            newTypeStr = "repeater";
                        }
                        else
                        {
                            newAccessType = ModemAccessType.Master;
                            newTypeStr = "master";
                        }

                        MessageBoxResult result = MessageBox.Show("Are your sure you want to change the access type of this headend to " + newTypeStr + "?",
                                                                    "Access Type change warning", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                        if (result == MessageBoxResult.Yes)
                        {


                            this.Cursor = Cursors.Wait;
                            if (dev.ChangeAccessType(newAccessType))
                            {
                                MessageBox.Show("The application has changed the access type.", "FS-Config - Access Type changed", MessageBoxButton.OK, MessageBoxImage.Information);
                            }
                            else
                            {
                                MessageBox.Show("The application has encountered a problem changing the access type.",
                                                "FS-Config - Access Type changed error", MessageBoxButton.OK, MessageBoxImage.Error);
                            }
                            UpdateModemConfigButtons();
                            this.Cursor = Cursors.Arrow;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ShowErrors(ex.Message);
                this.Cursor = Cursors.Arrow;
            }
        }

        private void modemChangeCouplingButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (deviceListView.SelectedItems.Count == 0)
                    MessageBox.Show("Select a device in the list view",
                                    "FS-Config - Coupling Type change error", MessageBoxButton.OK, MessageBoxImage.Error);
                else if (deviceListView.SelectedItems.Count > 1)
                    MessageBox.Show("Select only one device at a time in the list view",
                                    "FS-Config - Coupling Type change error", MessageBoxButton.OK, MessageBoxImage.Error);
                else
                {
                    YDevice dev = (YDevice)deviceListView.SelectedItem; // kvp.Value;

                    if (dev.Modem.AccesType != ModemAccessType.Repeater && dev.Modem.AccesType != ModemAccessType.Master)
                        MessageBox.Show("The selected device is not of type Master or Repeater",
                                "FS-Config - Coupling Type change error", MessageBoxButton.OK, MessageBoxImage.Error);
                    else
                    {
                        ModemCouplingType coupling;
                        string couplingCmd = modemChangeCouplingButton.Content as string;
                        if (couplingCmd.EndsWith("Coax"))
                            coupling = ModemCouplingType.Coax;
                        else
                            coupling = ModemCouplingType.Inductive;

                        MessageBoxResult result = MessageBox.Show("Are your sure you want to change the coupling type of this headend to " + dev.ModemNotSelectedCouplingTypeName + "?",
                                                                    "Coupling Type change warning", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                        if (result == MessageBoxResult.Yes)
                        {


                            this.Cursor = Cursors.Wait;

                            if (dev.ChangeCouplingType(coupling))
                            {
                                MessageBox.Show("The application has changed the coupling type.", "FS-Config - Coupling Type changed", MessageBoxButton.OK, MessageBoxImage.Information);
                            }
                            else
                            {
                                MessageBox.Show("The application has encountered a problem changing the coupling type.",
                                                "FS-Config - Coupling Type changed error", MessageBoxButton.OK, MessageBoxImage.Error);
                            }
                            UpdateModemConfigButtons();
                            this.Cursor = Cursors.Arrow;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ShowErrors(ex.Message);
                this.Cursor = Cursors.Arrow;
            }
        }

        private void loggerSaveButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                SaveLogToDisk();
            }
            catch (Exception ex)
            {
                ShowErrors(ex.Message);
            }
        }
                
        private void SaveLogToDisk()
        {
            // Configure save file dialog box

            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.FileName = "ScanLog"; // Default file name
            dlg.DefaultExt = ".txt"; // Default file extension
            dlg.Filter = "csv documents (.txt)|*.txt"; // Filter files by extension
            dlg.Title = "Save scan log dialog";
            // Show save file dialog box
            Nullable<bool> result = dlg.ShowDialog();

            // Process save file dialog box results
            if (result == true)
            {
                // Save document
                string filename = dlg.FileName;
                FileStream fs = File.Open(filename, FileMode.Create);
                string header = "BPL Network Scan Log\r\n" + DateTime.Now.ToString() + "\r\n";
                fs.Write(Encoding.ASCII.GetBytes(header), 0, header.Length);
                //byte[] endLineBuf = new byte[] { 0xD, 0XA };
                IEnumerable<string> logMessages = GetLogMessageList();
                foreach (string message in logMessages)
                {
                    string textLine = message + "\r\n";
                    byte[] buf = Encoding.UTF8.GetBytes(textLine);
                    fs.Write(buf, 0, buf.Length);
                    //fs.Write(endLineBuf,0,2);
                }
                fs.Close();
            }
        }

        private void modemResetButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (modemMACTextBox.Text != "")
                {
                    if (deviceListView.SelectedItems.Count == 0)
                        MessageBox.Show("Select a device in the list view",
                                        "FS-Config - Reset Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    else if (deviceListView.SelectedItems.Count > 1)
                        MessageBox.Show("Select only one device at a time in the list view",
                                        "FS-Config - Reset Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    else
                    {

                        MessageBoxResult result = MessageBox.Show("Are your sure you want to reset this modem?",
                                                                    "Reset warning", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                        if (result == MessageBoxResult.Yes)
                        {
                            YDevice dev = (YDevice)deviceListView.SelectedItem; // kvp.Value;
                            dev.Modem.Reset();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ShowErrors(ex.Message);
                this.Cursor = Cursors.Arrow;
            }
        }

        private void getFirmWareVersion_Click(object sender, RoutedEventArgs e)
        {
                    try
            {
                if (deviceListView.SelectedItems.Count == 0)
                    MessageBox.Show("Select a device in the list view",
                                    "FS-Config - Read/Write change error", MessageBoxButton.OK, MessageBoxImage.Error);
                else if (deviceListView.SelectedItems.Count > 1)
                    MessageBox.Show("Select only one device at a time in the list view",
                                    "FS-Config - Read/Write change error", MessageBoxButton.OK, MessageBoxImage.Error);
                else
                {
                    YDevice dev = (YDevice)deviceListView.SelectedItem; // kvp.Value;

                   

                        
                            this.Cursor = Cursors.Wait;


                            MessageBox.Show(dev.getmodemFirmwareVersion(), "FS-Config - About", MessageBoxButton.OK, MessageBoxImage.Information);
                           
                           
                            UpdateModemConfigButtons();
                            this.Cursor = Cursors.Arrow;
                       
                   
                }
            }
            catch (Exception ex)
            {
                ShowErrors(ex.Message);
                this.Cursor = Cursors.Arrow;
            }
        
        }

       
        private void FactoryRestore_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (deviceListView.SelectedItems.Count == 0)
                    MessageBox.Show("Select a device in the list view",
                                    "FS-Config - Restore error", MessageBoxButton.OK, MessageBoxImage.Error);
                else if (deviceListView.SelectedItems.Count > 1)
                    MessageBox.Show("Select only one device at a time in the list view",
                                    "FS-Config - Restore error", MessageBoxButton.OK, MessageBoxImage.Error);
                else
                {

                    MessageBoxResult result = MessageBox.Show("Are your sure you want to Restore this Device?",
                                                                    "Restore warning", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                    if (result == MessageBoxResult.Yes)
                    {
                        YDevice dev = (YDevice)deviceListView.SelectedItem; // kvp.Value;
                        this.Cursor = Cursors.Wait;
                        dev.getmodemFactoryRestored();
                        UpdateModemConfigButtons();
                        this.Cursor = Cursors.Arrow;
                        MessageBox.Show("Factory settings Restored", "FS-Config - Status", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                ShowErrors(ex.Message);
                this.Cursor = Cursors.Arrow;
            }

        }

        private void buttonRebootDevice_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (deviceListView.SelectedItems.Count == 0)
                    MessageBox.Show("Select a device in the list view",
                                    "FS-Config - Reboot error", MessageBoxButton.OK, MessageBoxImage.Error);
                else if (deviceListView.SelectedItems.Count > 1)
                    MessageBox.Show("Select only one device at a time in the list view",
                                    "FS-Config - Reboot error", MessageBoxButton.OK, MessageBoxImage.Error);
                else
                {
                    MessageBoxResult result = MessageBox.Show("Are your sure you want to Reboot this Device?",
                                                                    "Reboot warning", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                    if (result == MessageBoxResult.Yes)
                    {
                        YDevice dev = (YDevice)deviceListView.SelectedItem; // kvp.Value;
                        this.Cursor = Cursors.Wait;
                        dev.RebootYDevice();
                        UpdateModemConfigButtons();
                        this.Cursor = Cursors.Arrow;
                        MessageBox.Show("Device Rebooted", "FS-Config - Status", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                ShowErrors(ex.Message);
                this.Cursor = Cursors.Arrow;
            }
        }

        private void QuitSession_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (deviceListView.SelectedItems.Count == 0)
                    MessageBox.Show("Select a device in the list view",
                                    "FS-Config - Session error", MessageBoxButton.OK, MessageBoxImage.Error);
                else if (deviceListView.SelectedItems.Count > 1)
                    MessageBox.Show("Select only one device at a time in the list view",
                                    "FS-Config - Session error", MessageBoxButton.OK, MessageBoxImage.Error);
                else
                {
                     MessageBoxResult result = MessageBox.Show("Are your sure you want to Close this Session?",
                                                                    "Session warning", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                     if (result == MessageBoxResult.Yes)
                     {
                         YDevice dev = (YDevice)deviceListView.SelectedItem; // kvp.Value;
                         this.Cursor = Cursors.Wait;
                         dev.getSessionClosed();
                         UpdateModemConfigButtons();
                         this.Cursor = Cursors.Arrow;
                         MessageBox.Show("Device Session Closed", "FS-Config - Status", MessageBoxButton.OK, MessageBoxImage.Information);
                     }
                }
            }
            catch (Exception ex)
            {
                ShowErrors(ex.Message);
                this.Cursor = Cursors.Arrow;
            }
        }

        private void ChangeMultPowerClick(object sender, RoutedEventArgs e)
        {
            ComboBoxItem item = (ComboBoxItem)TmultComboBox.SelectedItem;
            string choice = (string)item.Tag;
            System.Console.WriteLine(choice);
                try
                {
                    if (deviceListView.SelectedItems.Count == 0)
                        MessageBox.Show("Select a device in the list view",
                                        "FS-Config - Signal Amplification error", MessageBoxButton.OK, MessageBoxImage.Error);
                    else if (deviceListView.SelectedItems.Count > 1)
                        MessageBox.Show("Select only one device at a time in the list view",
                                        "FS-Config - Signal Amplification error", MessageBoxButton.OK, MessageBoxImage.Error);
                    else
                    {
                       

                        MessageBoxResult result = MessageBox.Show("Are your sure you want to Change Signal Amplification?",
                                                                    "Signal Amplification", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                        if (result == MessageBoxResult.Yes)
                        {
                            YDevice dev = (YDevice)deviceListView.SelectedItem; // kvp.Value;
                            this.Cursor = Cursors.Wait;
                        //    System.Console.WriteLine("1111");
                            if (dev.ChangeMultPower(choice))
                            {
                                MessageBox.Show("The application has changed the Signal Amplification to " + choice, "FS-Config - Signal Amplification Power Modified", MessageBoxButton.OK, MessageBoxImage.Information);

                            }
                            else
                            {
                                MessageBox.Show("The application has encountered a problem changing the Signal Amplification Power .",
                                                "FS-Config - Signal Amplification Power Change error", MessageBoxButton.OK, MessageBoxImage.Error);
                            }

                            UpdateModemConfigButtons();
                            this.Cursor = Cursors.Arrow;
                        }
                    }
                }
                catch (Exception ex)
                {
                    ShowErrors(ex.Message);
                    this.Cursor = Cursors.Arrow;
                }
            
        }

        private void PowerMaskEnable_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (deviceListView.SelectedItems.Count == 0)
                    MessageBox.Show("Select a device in the list view",
                                    "FS-Config - Power Mask change error", MessageBoxButton.OK, MessageBoxImage.Error);
                else if (deviceListView.SelectedItems.Count > 1)
                    MessageBox.Show("Select only one device at a time in the list view",
                                    "FS-Config - Power Mask change error", MessageBoxButton.OK, MessageBoxImage.Error);
                else
                {
                    YDevice dev = (YDevice)deviceListView.SelectedItem; // kvp.Value;

                    if (dev.Modem.AccesType != ModemAccessType.Repeater && dev.Modem.AccesType != ModemAccessType.Master)
                        MessageBox.Show("The selected device is not of type Master or Repeater",
                                "FS-Config - Power Mask change error", MessageBoxButton.OK, MessageBoxImage.Error);
                    else
                    {

                        MessageBoxResult result = MessageBox.Show("Are your sure you want to Enable Power Mask of this headend ?",
                                                                    "Power Mask change warning", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                        if (result == MessageBoxResult.Yes)
                        {


                            this.Cursor = Cursors.Wait;

                            if (dev.ChangePowerMaskEnable())
                            {
                                MessageBox.Show("The application has Enabled Power Mask.", "FS-Config - Power Mask change error", MessageBoxButton.OK, MessageBoxImage.Information);
                            }
                            else
                            {
                                MessageBox.Show("The application has encountered a problem changing the Power Mask .",
                                                "FS-Config - Power Mask change error", MessageBoxButton.OK, MessageBoxImage.Error);
                            }
                            UpdateModemConfigButtons();
                            this.Cursor = Cursors.Arrow;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ShowErrors(ex.Message);
                this.Cursor = Cursors.Arrow;
            }
        }

        private void PowerMaskDisable_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (deviceListView.SelectedItems.Count == 0)
                    MessageBox.Show("Select a device in the list view",
                                    "FS-Config - Power Mask change error", MessageBoxButton.OK, MessageBoxImage.Error);
                else if (deviceListView.SelectedItems.Count > 1)
                    MessageBox.Show("Select only one device at a time in the list view",
                                    "FS-Config - Power Mask change error", MessageBoxButton.OK, MessageBoxImage.Error);
                else
                {
                    YDevice dev = (YDevice)deviceListView.SelectedItem; // kvp.Value;

                    if (dev.Modem.AccesType != ModemAccessType.Repeater && dev.Modem.AccesType != ModemAccessType.Master)
                        MessageBox.Show("The selected device is not of type Master or Repeater",
                                "FS-Config - Power Mask change error", MessageBoxButton.OK, MessageBoxImage.Error);
                    else
                    {

                        MessageBoxResult result = MessageBox.Show("Are your sure you want to Disable Power Mask of this headend ?",
                                                                    "Power Mask change warning", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                        if (result == MessageBoxResult.Yes)
                        {


                            this.Cursor = Cursors.Wait;

                            if (dev.ChangePowerMaskDisable())
                            {
                                MessageBox.Show("The application has Disabled Power Mask.", "FS-Config - Power Mask change error", MessageBoxButton.OK, MessageBoxImage.Information);
                            }
                            else
                            {
                                MessageBox.Show("The application has encountered a problem changing the Power Mask .",
                                                "FS-Config - Power Mask change error", MessageBoxButton.OK, MessageBoxImage.Error);
                            }
                            UpdateModemConfigButtons();
                            this.Cursor = Cursors.Arrow;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ShowErrors(ex.Message);
                this.Cursor = Cursors.Arrow;
            }
        }

       
        private void defaultconfiig(object sender, RoutedEventArgs e)
        {
            
            try
            {
                Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
                dlg.FileName = ""; // Default file name
                dlg.DefaultExt = ".ftp"; // Default file extension
                dlg.Filter = "ftp file (.ftp)|*.ftp"; // Filter files by extension

                // Show save file dialog box
                Nullable<bool> result = dlg.ShowDialog();

                // Process save file dialog box results
                if (result == true)
                {
                    if (deviceListView.SelectedItems.Count > 0)
                        DefaultProgram.IsEnabled = true;

                    string filename = dlg.FileName;
                    defaultConfigNameTextBox.Text = filename;
                }
                else
                    DefaultProgram.IsEnabled = false;
            }
            catch (Exception ex)
            {
                ShowErrors(ex.Message);
            }
        }

        private void ConfigUpload_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
                dlg.FileName = ""; // Default file name
                dlg.DefaultExt = ".ftp"; // Default file extension
                dlg.Filter = "ftp file (.ftp)|*.ftp"; // Filter files by extension

                // Show save file dialog box
                Nullable<bool> result = dlg.ShowDialog();

                // Process save file dialog box results
                if (result == true)
                {
                    if (deviceListView.SelectedItems.Count > 0)
                        NvramReset.IsEnabled = true;

                    string filename = dlg.FileName;
                    config.Text = filename;
                }
                else
                    NvramReset.IsEnabled = false;
            }
            catch (Exception ex)
            {
                ShowErrors(ex.Message);
            }
        }

        private void DefaultProgram_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ModemAccessType modemType = ModemAccessType.Unknown;

                if (modemFileNameTextBox.Text != "")
                {
                    MessageBoxResult result = MessageBox.Show("Are your sure you want to Load Default Configurations?",
                                                                "Load Configurations warning", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                    if (result == MessageBoxResult.Yes)
                    {
                        List<YDevice> devs = new List<YDevice>();//_yNet.GetDeviceList("Modem");

                        foreach (IYDeviceInfo y in deviceListView.SelectedItems)
                        {
                            YDevice dev = (YDevice)deviceListView.SelectedItem; // kvp.Value;
                            if (modemType == ModemAccessType.Unknown)
                                modemType = dev.Modem.AccesType;
                            else if (modemType != dev.Modem.AccesType)
                            {
                                MessageBox.Show("Master and repeater modems can't be updated at the same time. Change your modem selection.",
                                            "FS-Config - Configuration Error", MessageBoxButton.OK, MessageBoxImage.Error);
                                return;
                            }
                            if (dev.loadDefaultConfig(modemFileNameTextBox.Text))
                            {
                                MessageBox.Show("Factory Settings Restored",
                                             "FS-Config - Restore", MessageBoxButton.OK);
                            }
                            else
                            {
                                MessageBox.Show("The application has encountered a problem with the Tftp server. The Configuration process has stopped.",
                                                "FS-Config - Configuration Error", MessageBoxButton.OK, MessageBoxImage.Error);
                            }
                            //if(dev.Modem.AccesType ==  ModemAccessType.Repeater)
                         //   devs.Add(dev);
                        }

                       
                    }
                }
            }
            catch (Exception ex)
            {
                ShowErrors(ex.Message);
            }
        }

        private void NvramReset_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ModemAccessType modemType = ModemAccessType.Unknown;

                if (modemFileNameTextBox.Text != "")
                {
                    MessageBoxResult result = MessageBox.Show("Are your sure you want to Load Default Configurations?",
                                                                "Load Configurations warning", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                    if (result == MessageBoxResult.Yes)
                    {
                        List<YDevice> devs = new List<YDevice>();//_yNet.GetDeviceList("Modem");

                        foreach (IYDeviceInfo y in deviceListView.SelectedItems)
                        {
                            YDevice dev = (YDevice)deviceListView.SelectedItem; // kvp.Value;
                            if (modemType == ModemAccessType.Unknown)
                                modemType = dev.Modem.AccesType;
                            else if (modemType != dev.Modem.AccesType)
                            {
                                MessageBox.Show("Master and repeater modems can't be updated at the same time. Change your modem selection.",
                                            "FS-Config - Configuration Error", MessageBoxButton.OK, MessageBoxImage.Error);
                                return;
                            }
                            if (dev.UploadConfnvram(config.Text))
                            {
                                MessageBox.Show("Nvram Restored",
                                              "FS-Config - Restore", MessageBoxButton.OK);
                            }
                            else
                            {
                                MessageBox.Show("The application has encountered a problem with the Tftp server. The Configuration process has stopped.",
                                                "FS-Config - Configuration Error", MessageBoxButton.OK, MessageBoxImage.Error);
                            }
                            //if(dev.Modem.AccesType ==  ModemAccessType.Repeater)
                            //   devs.Add(dev);
                        }


                    }
                }
            }
            catch (Exception ex)
            {
                ShowErrors(ex.Message);
            }
        }
        private void saveMacAddress() {
           
            this.Cursor = Cursors.Wait;
            ObixEntry[] entries = GetMacAddress();
          
            //YDevice dev = _yNet.Devices[IPAddress.Parse(_YdevCollection[deviceListView.SelectedIndex].Ip)];
            //dev.
            GetNumOfThreads();
          
            Y1G.WriteMacAddress(_yNet.SelectedY1gs, entries);
        
            _yNet.BeginWrite(_yNet.SelectedY1gs, null);
           
            ShowErrors();
           
            this.Cursor = Cursors.Arrow;
        }

        private void SaveMac_Click(object sender, RoutedEventArgs e)
        {
            
            try
            {
                if (_scanComplete)
                {
                    saveMacAddress();
                }
            }
            catch (Exception ex)
            {
            //    System.Console.Write("wqqw");
                ShowErrors(ex.Message);
                this.Cursor = Cursors.Arrow;
            }
        }

       
      

    }
 }
